<?php

namespace backend\models;

use common\helps\tools;
use Yii;
use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;
use yii\db\Exception;

/**
 * This is the model class for table "AuthRule".
 *
 */
class AuthRule extends ActiveRecord
{
    public $type;// 操作类型
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%auth_rule}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return[
            [['title','name','unique_key','level','pid'], 'trim'],
            [['id','title','name','level','pid','unique_key','type'], 'required', 'message'=>'{attribute}不能为空'],
            [['id','type','level'], 'match', 'pattern' => '/^[1-9][0-9]*$/','message'=>'{attribute}值无效'],
//            [['title','unique_key','name'], 'unique', 'message'=>'{attribute}已存在'],
        ];
    }


    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => '节点id',
            'pid'=>'父级节点',
            'level'=>'节点类型',
            'title' => '节点名称',
            'name'=>'节点地址',
            'unique_key'=>'唯一字段',
            'type'=>'当前操作类型',
            'ismenu'=>'菜单显示',
        ];
    }

    public function scenarios()
    {
        return [
            'default' => [
                'id',
                'pid',
                'module',
                'level',
                'name',
                'title',
                'status',
                'unique_key',
                'ismenu',
                'sorts',
                'created_at',
                'updated_at',
                'deleted_at',
            ],
            'pre_create' => [
                'pid',
                'module',
                'level',
                'name',
                'title',
                'status',
                'unique_key',
                'ismenu',
                'sorts',
                'created_at',
                'updated_at',
                'deleted_at',
                'type',
            ],
            'create' => [
                'pid',
                'module',
                'level',
                'name',
                'title',
                'status',
                'unique_key',
                'ismenu',
                'sorts',
                'created_at',
                'updated_at',
                'deleted_at',
            ],
            'update' => [
                'id',
                'pid',
                'module',
                'level',
                'name',
                'title',
                'status',
                'unique_key',
                'ismenu',
                'sorts',
                'created_at',
                'updated_at',
                'deleted_at'
            ],
        ];
    }



    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }


    /**
     * 获取权限管理列表
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getAuthRuleList(){
        $list=$this->find()->select('*')->where(['status'=>1])->orderBy('sorts ASC,id ASC')->asArray()->all();
        return empty($list)?array():$list;

    }

    /**
     * 删除节点
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function deleteAuthRule($id){
        $rule_info = $this->find()->where(['id'=>$id])->asArray()->one();
        if(empty($rule_info)) return false;
        $t = static::getDb()->beginTransaction();
        try {
            $child=$this->find()->where(['pid'=>$rule_info['id']])->asArray()->all();
            if(count($child)){
                $update_ids = array_column($child,'id');
                array_push($update_ids,$rule_info['id']);
            }else{
                $update_ids[] = $rule_info['id'];
            }
            $update_ids = implode(',',$update_ids);
            $this::updateAll(['status' => 2,'deleted_at'=>time()],'id in ('. $update_ids.')');
            $this->refresh();
            $t->commit();
            //删除成功后需要更新权限相关缓存
            tools::delAuthCache();
            return true;
        }catch (Exception $e) {
            $t->rollback();
            return false;
        }

    }


    /**
     * 新增与编辑节点
     * @param $param
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function editRole($param){
        if($param['type']>1){ //编辑
            $model = static::findOne(['id' =>$param['id']]);
            if(empty($model)) return array('error'=>'未查询到相关信息');
            $model->scenario = 'update';
        }else{
            $model = new self();
            $model->scenario = 'create';
            unset($param['id']);
        }
        if(intval($param['pid'])>0){
            $p_info = static::findOne(['id' =>$param['pid']])->toArray();
            if(intval($p_info['level'])!= intval($param['level']-1)){
                return array('error'=>'节点类型选择与上级节点不匹配');
            }
        }
        $t = static::getDb()->beginTransaction();
        try {
            $model->setAttributes($param, false);
            if (!$model->save()) {
                return array('error'=>'操作失败');
            }else{
                $t->commit();
                //更新权限缓存
                tools::delAuthCache();
                return array('error'=>'');
            }
        }catch (Exception $e){
            $t->rollback();
            return array('error'=>'操作失败');
        }

    }


}
